<template>
    <div class="feedback-wrapper">
      <div class="feedback-container">
        <div class="feecback-type">
          <h4 class="van-hairline--bottom"><b>*</b> 反馈类型</h4>
          <div class="types">
            <ul class="clearfix">
              <li v-for="(item,index) in feedbackType" :key="index" :class="{'tag_active':tagActive === index}" @click="selectFeedbackType(index)">
                {{item}}
              </li>
            </ul>
          </div>
          <div class="feedback-line"></div>
        </div>
        <div class="problem-description">
          <h4 class="van-hairline--bottom"><b>*</b> 问题描述</h4>
          <div class="descripe-text">
            <textarea type="text" placeholder="请简要描述您的问题或建议，我们将及时跟进解决。（建议添加相关问题截图）" v-model="problemValue"></textarea>
          </div>
          <div class="feedback-line"></div>
        </div>
        <div class="upload-photo">
          <h4 class="van-hairline--bottom">上传照片<b>（最多上传9张）</b></h4>
          <div class="photos clearfix">
            <div class="uploaderImgs fl" v-for="(item,index) in uploaderImgArray" :key="index">
              <div class="iconPosition">
                <img :src="item" @click="imgPreview(index)">
                <i class="photo-delete" @click="deletePhoto(index)"></i>
              </div>
            </div>
            <div v-if="isShowFileInput">
              <van-uploader :after-read="onRead" class="fl" multiple>
                <i class="photo-icon"></i>
              </van-uploader>
            </div>
          </div>
        </div>
      </div>
      <div class="register-btn">
        <van-button size="large" round class="register-submit-btn" @click="submit">提交</van-button>
      </div>
    </div>
</template>

<script>
    import ajax from '../../module/ajax/public'
    import { Tag, Uploader,Button, Notify, ImagePreview,Toast } from 'vant'
    import $ from 'jquery'
    import COS from 'cos-js-sdk-v5'

    export default {
        name: "Feedback",
        components:{
          [Tag.name]: Tag,
          [Uploader.name]: Uploader,
          [Button.name]: Button,
        },
        data () {
          return {
            feedbackType:['bug反馈','产品建议','问题投诉','其他'],
            tagActive:1,
            problemValue:'',
            uploaderImgArray:[],
          }
        },
        computed:{
          isShowFileInput(){
            // console.log('this.uploaderImgArray',this.uploaderImgArray)
            if(this.uploaderImgArray.length >= 9){
              return false
            }else{
              return true
            }
          }
        },
        methods:{
          //反馈类型
          selectFeedbackType(index){
            this.tagActive = index;
          },
          //上传照片
          onRead(file){
            // console.log(file)
            Toast.loading({
              message:'图片上传中',
              duration:0,
              loadingType: 'spinner'
            })
            const cos = new COS({
              // 必选参数
              getAuthorization: function (options, callback) {
                $.post(`${process.env.API_ROOT}/cos/getTempKeys`, {
                  bucket: options.Bucket,
                  region: options.Region
                }, function (res) {
                  const data = res.data
                  callback({
                    TmpSecretId: data.credentials.tmpSecretId,
                    TmpSecretKey: data.credentials.tmpSecretKey,
                    XCosSecurityToken: data.credentials.sessionToken,
                    ExpiredTime: data.expiredTime
                  })
                })
              }
            })
            let _this = this
            let myDate = new Date()
            const fileName = 'feedbackImg' + myDate.getFullYear() + (myDate.getMonth() + 1) + myDate.getDate() + myDate.getHours() + myDate.getMinutes() + myDate.getSeconds() + Math.floor(Math.random() * 100 + 1)
            const fileNameArray = []
            const fileArray = [];
            if(file.length > 0 ){
              for(let i in file){
                fileNameArray[i] = 'feedbackImg' + myDate.getFullYear() + (myDate.getMonth() + 1) + myDate.getDate() + myDate.getHours() + myDate.getMinutes() + myDate.getSeconds() + Math.floor(Math.random() * 100 + 1)
                // console.log(i,':',file[i].file)
                fileArray.push({
                  Bucket: 'tupu-1259317410',
                  Region: 'ap-shanghai',
                  Key: fileNameArray[i],
                  Body: file[i].file,
                })
                if(fileArray.length >= 9){
                  fileArray.length = 9
                }
              }
            }else{
              fileArray.push({
                Bucket: 'tupu-1259317410',
                Region: 'ap-shanghai',
                Key: fileName,
                Body: file.file,
              })
            }
            // console.log('fileNameArray',fileNameArray);
            // console.log('fileArray',fileArray)
            cos.uploadFiles({
              files: fileArray,
              SliceSize: 1024 * 1024,
              onProgress: function (info) {
                // var percent = parseInt(info.percent * 10000) / 100;
                // var speed = parseInt(info.speed / 1024 / 1024 * 100) / 100;
                // console.log('进度：' + percent + '%; 速度：' + speed + 'Mb/s;');
              },
              onFileFinish: function (err, data, options) {

              },
            }, function (err, data) {
              console.log(data.files)
              const dataFiles = data.files
              dataFiles.forEach(value => {
                // console.log(value.data)
                if(value.data.statusCode === 200){
                  _this.uploaderImgArray.push(_this.GLOBAL.CDNimgUrl + value.options.Key)
                  Toast.clear()
                  Notify({
                    message: '图片上传成功',
                    background: '#0085ca'
                  });
                }else {
                    Toast.clear()
                    Notify('图片上传失败')
                    console.log(err)
                }
                // console.log(_this.uploaderImgArray)
              })
            })
          },
          //删除照片
          deletePhoto(index){
            this.uploaderImgArray.splice(index,1)
          },
          //图片预览
          imgPreview(index){
            ImagePreview({
              images: this.uploaderImgArray,
              startPosition:index,
              className:'previewUploaderImg'
            })
          },
          //提交
          submit(){
            if(!this.problemValue){
              Notify('请填写问题描述')
              return
            }
            ajax.doAction({
              url: '/user/feedback',
              type: 'POST',
              items: {
                type: this.tagActive+1,
                content: this.problemValue,
                images:this.uploaderImgArray,
              },
              successMsg: {
                isshow: true,
                msg: '反馈已提交'
              },
              successCallback: (data) => {
                setTimeout(() => {
                  this.$router.push('/user')
                },1000)
              },
              errorCallback: (data) => {
                console.log('请求失败')
              }
            })
          }
        }
    }
</script>

<style>
  .feedback-container .types li{
    margin-right: 12px;
    padding: 6px;
    color: #E5E5E5;
    font-size: 12px;
    border-radius: 30px;
    border: 1px solid #e5e5e5;
    float: left;
  }
  .feedback-container .types li.tag_active{
    color:#0085ca;
    border: 1px solid #0085ca;
  }
  .feedback-container .feedback-line{
    width: 100%;
    height: 8px;
    background: #F2F3F7;
  }
  .feedback-container h4{
    padding-left: 12px;
    padding-top: 12px;
    padding-bottom: 12px;
    font-size: 15px;
    font-weight: normal;
  }
  .feedback-container b{
    color: red;
    vertical-align: middle;
  }
  .feedback-container .types, .feedback-container .descripe-text, .feedback-container .photos{
    padding: 20px 12px;
  }
  .feedback-container .descripe-text textarea{
    border: 0;
    outline: 0;
    width: 100%;
    font-size: 12px;
    line-height: 20px;
    padding: 0;
    resize: none;
  }
  .feedback-container .descripe-text textarea::placeholder{
    color:#BFBFBF;
  }
  .feedback-container .upload-photo h4 b{
    font-weight: normal;
    color: #bbb;
    font-size: 10px;
  }
  .feedback-container .van-uploader{
    border: 1px dashed #bfbfbf;
    border-radius: 3px;
    width: 63px;
    height: 63px;
    position: relative;
  }
  .feedback-container .van-uploader .photo-icon{
    position: absolute;
    left:50%;
    top:50%;
    transform: translate(-50%,-50%);
    width: 21px;
    height: 18px;
    background: url("/static/images/xiangji.png") no-repeat center;
    background-size: 100% 100%;
  }
  .feedback-container .uploaderImgs{
    width: 33.3%;
    border-radius: 3px;
    margin-bottom: 20px;
  }
  .feedback-container .uploaderImgs .iconPosition{
    position: relative;
    height: 65px;
    width: 65px;
  }
  .feedback-container .uploaderImgs img{
    border-radius: 3px;
  }
  .feedback-container .uploaderImgs .photo-delete{
    position: absolute;
    right: -12px;
    top: -12px;
    width: 24px;
    height: 24px;
    background: url("/static/images/delete.png") no-repeat center;
    background-size: 100% 100%;
  }
  .previewUploaderImg.van-image-preview .van-image-preview__image{
    width:auto;
    height: auto;
    max-width: 95%;
    max-height: 88%;
  }
</style>
